# https://www.luogu.com.cn/problem/P1013

N =readline.to_i() -1
RG=0...N
letters =readline.split(' ')
letters.shift
Errorcode ="ERROR!"
table=[]
for i in 1..N
	table << readline.split(' ').last(N)
end

num_to_value=[-1]*N
num_to_str=[""]*N
for i in RG
	if table[i] ==letters
		num_to_value[i]=0
		Zero||=letters[i]
		Zero_num||=i
		break
	end
end
if Zero.nil?
	puts Errorcode
end
#puts "zero == #{Zero}"
num_to_str[Zero_num]=Zero
#sum_eq_ten=[]
for row in RG
	for col in RG
		if table[row][col].size==2 && table[row][col][-1]==Zero
			One ||=table[row][col][0]
			One_num ||=letters.index(One)
			Ten ||=table[row][col]
			num_to_value[One_num]=1
			#sum_eq_ten<<[row,col]
		end
	end
end
if One.nil?
	puts Errorcode
end
#puts "One  == #{One}"
num_to_str[One_num]=One
i=One_num
One_str=table[One_num]
indeces=2
while One_str[i].size == 1
	j=letters.index(One_str[i])
	num_to_str[j]=One_str[i]
	num_to_value[j]=num_to_value[i]+1
	i=j
	indeces+=1
end
#puts "num_to_str= " ,num_to_str
#puts "num_to_value= ", num_to_value		

#puts num_to_value

def check()
	


letters.each_index{ |i|
	print "#{letters[i]}=#{num_to_value[i]} "
}
print "\n",indeces
	